package ru.bytedog.oiot.counter.bot.service.command;

import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.telegram.telegrambots.meta.api.objects.Message;
import ru.bytedog.oiot.counter.bot.bean.BotAnswer;
import ru.bytedog.oiot.counter.bot.service.ConfigService;
import ru.bytedog.oiot.counter.bot.entity.BotUser;
import ru.bytedog.oiot.counter.bot.service.UserService;

/**
 * Сервисная команда для отображения статистики бота
 */
@Service
public class StatCommand implements BotCommand {

    private final UserService service;

    private final ConfigService configService;

    public StatCommand(UserService service, ConfigService configService) {
        this.service = service;
        this.configService = configService;
    }

    @Override
    public CommandEnum getCommand() {
        return CommandEnum.STAT;
    }

    @Override
    public BotAnswer commandProcess(Message message) {
        String userChat = String.valueOf(message.getChatId());
        if (!configService.isAccessEnabled(message.getFrom().getUserName())) {
           return new DefaultCommand().commandProcess(message);
        }

        List<BotUser> allUsers = service.getAll();
        List<BotUser> regUsers = allUsers.stream()
                .filter(user -> StringUtils.isNoneEmpty(user.getOiotUserId(), user.getOiotUserToken()))
                .toList();

        BotAnswer answer = new BotAnswer();
        answer.setChatId(userChat);
        answer.setMessage(String.format("Всего пользователей: %s%nЗаполнивших регистрационные данные: %s%n%s%nНе заполнивших:%n%s",
                allUsers.size(), regUsers.size(), regUsers.stream()
                        .map(BotUser::getUsername)
                        .collect(Collectors.joining("\n")),
                allUsers.stream()
                        .filter(user -> !regUsers.contains(user))
                        .map(user -> String.format("%s;%s;%s;%s", user.getUsername(), user.getCreateDate(), user.getOiotUserToken(), user.getOiotUserId()))
                        .collect(Collectors.joining("\n"))));
        return answer;
    }
}
